package com.px.framework.aes;


import com.px.common.utils.AESUtil;
import com.px.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class CustomizeParamsFilter implements Filter {

    public static String key;

    @Value("${aes.key}")
    public void setKey(String key) {
        CustomizeParamsFilter.key=key;
    }

    public static boolean enabled;

    @Value("${aes.enabled}")
    public void setEnabled(boolean enabled) {
        CustomizeParamsFilter.enabled=enabled;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //参数处理
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Map<String, String[]> params = new HashMap<>();
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String httpMethod = request.getMethod();
        if (!enabled){
            filterChain.doFilter(request, response);
            return;
        }
        if("GET".equals(httpMethod)){
            Map<String, String[]> parameterMap = request.getParameterMap();
            String obj = null;
            for (String key : parameterMap.keySet()){
                obj = key;
                if (obj != null) {
                    break;
                }
            }
            if (StringUtils.isNotEmpty(obj))
            {
                try
                {
                    // 通过密钥解密参数,并转成Map
                    String deStr = AESUtil.aesDecrypt(obj,key);
                    if(StringUtils.isNotEmpty(deStr)){
                        Map<String, String> map = Arrays.stream(deStr.split("&"))
                                .collect(Collectors.toMap(s -> s.split("=")[0], s -> s.split("=")[1]));
                        for(String key : map.keySet()){
                            params.put(key,new String[]{map.get(key)});
                        }
                        HandleParamsDecryptHttpServletRequest req = new HandleParamsDecryptHttpServletRequest(request, params);
                        filterChain.doFilter(req, response);
                        return;
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
